//
//  MeLivePushViewController.m
//  MeLive
//
//  Created by liulei on 2017/5/10.
//  Copyright © 2017年 liulei. All rights reserved.
//

#import "MeLivePushViewController.h"
#import <TXRTMPSDK/TXLivePush.h>
#import <TXRTMPSDK/TXLiveSDKTypeDef.h>
#import <TXRTMPSDK/TXLiveSDKEventDef.h>
#import <TXRTMPSDK/TXLivePlayer.h>
#import "MeLivePushWaitView.h"
#import "objc/runtime.h"
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <sys/types.h>
#import <sys/sysctl.h>
#import <UIKit/UIKit.h>
#import <mach/mach.h>
#import "MePushMgr.h"

#define SEPARATE_STR @"###"
#define PLAYER_NUM_MAX 4

static  BOOL canEdit = NO;
static  char blockKey;

@interface MeLivePushViewController ()<MeLivePushWaitViewDelegate,TXLivePushListener,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    int                         _beauty_level;
    int                         _whitening_level;
    NSString                    *_strPublisUrl;
    BOOL                        _isPreviewing;
    UIView                      *preViewContainer;
    TXLivePush                  * _txLivePublisher;
    MeLivePushWaitView          *_waitPushView;
    UIView                      *_videoParentView;
    NSMutableArray              *_arryPlayUrls;
}
@property (copy, nonatomic)   NSMutableArray *imageArrs;
@property (strong, nonatomic) UIImageView *coverImageView;
@property (nonatomic, copy)   photoBlock photoBlock;
@property (strong, nonatomic) MeLiveInfoModel *hostInfo;

@end

@implementation MeLivePushViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
    //视频画面的父view
    _videoParentView = [[UIView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:_videoParentView];
    
    TXLivePushConfig* _config = [[TXLivePushConfig alloc] init];
    _config.frontCamera = YES;
    _txLivePublisher = [[TXLivePush alloc] initWithConfig:_config];
    
    _arryPlayUrls = [[NSMutableArray alloc] init];
    
    [self initUI];
    
    // 预览画面
    [self startRtmp];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
#if !TARGET_IPHONE_SIMULATOR
    //是否有摄像头权限
    AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (statusVideo == AVAuthorizationStatusDenied) {
        [self toastTip:@"获取摄像头权限失败，请前往隐私-相机设置里面打开应用权限"];
        return;
    }
    
    //    if (!_isPreviewing) {
    //        [_txLivePublisher startPreview:preViewContainer];
    //        _isPreviewing = YES;
    //    }
#endif
    
}

- (void)getRTMPPushUrl{
    WEAKSELF
    [[MePushMgr sharedInstance] getPusherUrlWithUserid:NullStringToString(@"5") isMobileShow:@"1" orientation:@"portrait" handler:^(int result, MeLiveInfoModel *liveInfo) {
        if (result==0) {
            weakSelf.hostInfo = liveInfo;
            weakSelf.rtmpPushUrl =  weakSelf.hostInfo.pushUrl;
            if ([liveInfo.state isEqualToString:@"P"]) {
                
                if (_isPreviewing) {
                    [_txLivePublisher stopPreview];
                    _isPreviewing = NO;
                }
                [weakSelf startRtmp];
                
            }else if ([liveInfo.state isEqualToString:@"F"]){
                
            }
        }
    }];
}

-(BOOL)startRtmp{
    
    if (_strPublisUrl.length == 0) {
        [self parseUrl:self.rtmpPushUrl];
        
        if (_strPublisUrl.length == 0) {
            _strPublisUrl = self.rtmpPushUrl;
        }
    }
    
    //是否有摄像头权限
    AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (statusVideo == AVAuthorizationStatusDenied) {
        [self toastTip:@"获取摄像头权限失败，请前往隐私-相机设置里面打开应用权限"];
        return NO;
    }
    
    //是否有麦克风权限
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        [self toastTip:@"获取麦克风权限失败，请前往隐私-麦克风设置里面打开应用权限"];
        return NO;
    }
    
    if(_txLivePublisher != nil)
    {
        
        TXLivePushConfig* _config = _txLivePublisher.config;
        // 美颜默认值是7
        [_txLivePublisher setBeautyFilterDepth:7 setWhiteningFilterDepth:3];
        _config.pauseFps = 10;
        _config.pauseTime = 300;
        _config.pauseImg = [UIImage imageNamed:@"live_pause_publish.png"];
        
        [_txLivePublisher setConfig:_config];
        
        _txLivePublisher.delegate = self;
        if (!_isPreviewing) {
            [_txLivePublisher startPreview:preViewContainer];
            _isPreviewing = YES;
        }
        
        if ([_strPublisUrl hasPrefix:@"rtmp://"]) {
            if ([_txLivePublisher startPush:_strPublisUrl] != 0) {
                NSLog(@"推流器启动失败");
                return NO;
            }
            return YES;
        }
    }
    
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    return YES;
}

- (void)stopRtmp {
    _strPublisUrl = @"";
    if(_txLivePublisher != nil)
    {
        _txLivePublisher.delegate = nil;
        [_txLivePublisher stopPreview];
        _isPreviewing = NO;
        [_txLivePublisher stopPush];
    }
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

// RTMP 推流事件通知
#pragma - TXLivePushListener
-(void) appendLog:(NSString*) evt time:(NSDate*) date mills:(int)mil
{


}

-(void) onPushEvent:(int)EvtID withParam:(NSDictionary*)param;
{
    NSDictionary* dict = param;

    dispatch_async(dispatch_get_main_queue(), ^{
        if (EvtID == PUSH_ERR_NET_DISCONNECT) {
            //            [self clickPublish:_btnPublish];
        }else if(EvtID == PUSH_WARNING_HW_ACCELERATION_FAIL){
            _txLivePublisher.config.enableHWAcceleration = false;
            //            [_btnHardware setImage:[UIImage imageNamed:@"quick2"] forState:UIControlStateNormal];
        }else if (EvtID == PUSH_EVT_PUSH_BEGIN){
           
            
        }
        //        NSLog(@"evt:%d,%@", EvtID, dict);
        long long time = [(NSNumber*)[dict valueForKey:EVT_TIME] longLongValue];
        int mil = time % 1000;
        NSDate* date = [NSDate dateWithTimeIntervalSince1970:time/1000];
        NSString* Msg = (NSString*)[dict valueForKey:EVT_MSG];
        [self appendLog:Msg time:date mills:mil];
    });
}

// TXLivePushListener回调
-(void) onNetStatus:(NSDictionary*) param
{
    NSDictionary* dict = param;
    
    NSString * streamID = [dict valueForKey:STREAM_ID];
    if ([streamID isEqualToString:_strPublisUrl] != YES)
    {        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
       
        
    });
}

/**
 @method 获取指定宽度width的字符串在UITextView上的高度
 @param textView 待计算的UITextView
 @param width 限制字符串显示区域的宽度
 @result float 返回的高度
 */
- (float) heightForString:(UITextView *)textView andWidth:(float)width{
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}
- (void) toastTip:(NSString*)toastInfo
{
    CGRect frameRC = [[UIScreen mainScreen] bounds];
    frameRC.origin.y = frameRC.size.height - 110;
    frameRC.size.height -= 110;
    __block UITextView * toastView = [[UITextView alloc] init];
    
    toastView.editable = NO;
    toastView.selectable = NO;
    
    frameRC.size.height = [self heightForString:toastView andWidth:frameRC.size.width];
    
    toastView.frame = frameRC;
    
    toastView.text = toastInfo;
    toastView.backgroundColor = [UIColor whiteColor];
    toastView.alpha = 0.5;
    
    [self.view addSubview:toastView];
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
    
    dispatch_after(popTime, dispatch_get_main_queue(), ^(){
        [toastView removeFromSuperview];
        toastView = nil;
    });
}

- (void)initUI{
    
    _waitPushView = [[MeLivePushWaitView alloc] initWithFrame:self.view.frame];
    _waitPushView.delegate = self;
    _waitPushView.coverPicStr = @"";
    [self.view addSubview:_waitPushView];
    
    CGRect previewFrame = self.view.bounds;
    preViewContainer = [[UIView alloc] initWithFrame:previewFrame];
    [self.view insertSubview:preViewContainer atIndex:0];
    preViewContainer.center = self.view.center;
}

- (void)parseUrl:(NSString *)urlsets
{
    NSArray * liveUrlArry = [urlsets componentsSeparatedByString:SEPARATE_STR];
    
    if ([liveUrlArry count] > 0) {
        _strPublisUrl = [liveUrlArry objectAtIndex:0];
    }
    
    if ([liveUrlArry count] > 1) {
        [_arryPlayUrls removeAllObjects];
        size_t count = [liveUrlArry count]-1 > PLAYER_NUM_MAX ? PLAYER_NUM_MAX : [liveUrlArry count]-1;
        for (int i=1; i<count+1; ++i) {
            [_arryPlayUrls addObject:[liveUrlArry objectAtIndex:i]];
        }
    }
}

-(int)checkPlayUrl:(NSString*)playUrl {
    if (!([playUrl hasPrefix:@"http:"] || [playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"rtmp:"] )) {
        [self toastTip:@"播放地址不合法，目前仅支持rtmp,flv,hls,mp4播放方式!"];
        return -1;
    }
    
    if ([playUrl hasPrefix:@"rtmp:"]) {
        return PLAY_TYPE_LIVE_RTMP;
    } else if (([playUrl hasPrefix:@"https:"] || [playUrl hasPrefix:@"http:"]) && [playUrl rangeOfString:@".flv"].length > 0) {
        return PLAY_TYPE_LIVE_FLV;
    } else{
        [self toastTip:@"播放地址不合法，直播目前仅支持rtmp,flv播放方式!"];
        return -1;
    }
}


#pragma mark - MeLivePushWaitViewDelegate

- (void)didClickStartBtnInWaitPushView:(MeLivePushWaitView *)vsWaitPushView selectShareIndex:(NSInteger)shareIndex isNoCoverImage:(BOOL)isNoCoverImage{
//    if (isNoCoverImage) {
//        [gResMgr promptUIAlertView:kAlertTitle message:@"请上传直播封面!" cancelBtn:@"确定"];
//        return;
//    }
    [self getRTMPPushUrl];
}

- (void)didClickCloseBtnInWaitPushView:(MeLivePushWaitView *)vsWaitPushView{

    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didClickBeautyBtnInWaitPushView:(MeLivePushWaitView *)vsWaitPushView{
    _waitPushView.bottomView.hidden = YES;
    _waitPushView.vBeauty.hidden = NO;
}

- (void)didClickAddCoverPicInWaitPushView:(MeLivePushWaitView *)vsWaitPushView coverImage:(UIImageView *)coverImageView{
    _coverImageView = coverImageView;
    /*
     edit:照片需要裁剪:传YES,不需要裁剪传NO(默认NO)
     */
    WEAKSELF
    [self showCanEdit:YES photo:^(UIImage *photo) {
        
        coverImageView.image = photo;
        // 刷新界面
        [weakSelf.imageArrs removeAllObjects];
        [weakSelf.imageArrs addObject:UIImageJPEGRepresentation(photo,0.3)];
        [weakSelf updateLiveRoomCoverPic];
    }];
}

- (void)didSelectFilterInWaitPushView:(MeLivePushWaitView *)hsWaitPushView selectFilterIndex:(NSInteger)selectIndex{
    [self configFilterIndex:selectIndex];
}

- (void)configFilterIndex:(NSInteger)selectIndex{
    NSString* lookupFileName = @"";
    
    switch (selectIndex) {
        case FilterType_None:
            break;
        case FilterType_langman:
            lookupFileName = @"langman.png";
            break;
        case FilterType_qingxin:
            lookupFileName = @"qingxin.png";
            break;
        case FilterType_weimei:
            lookupFileName = @"weimei.png";
            break;
        case FilterType_fennen:
            lookupFileName = @"fennen.png";
            break;
        case FilterType_huaijiu:
            lookupFileName = @"huaijiu.png";
            break;
        case FilterType_landiao:
            lookupFileName = @"landiao.png";
            break;
        case FilterType_qingliang:
            lookupFileName = @"qingliang.png";
            break;
        case FilterType_rixi:
            lookupFileName = @"rixi.png";
            break;
        default:
            break;
    }
    NSString * path = [[NSBundle mainBundle] pathForResource:@"FilterResource" ofType:@"bundle"];
    if (path != nil && selectIndex != FilterType_None && _txLivePublisher != nil) {
        path = [path stringByAppendingPathComponent:lookupFileName];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        [_txLivePublisher setFilter:image];
    } else if(_txLivePublisher != nil) {
        [_txLivePublisher setFilter:nil];
    }
    
}

#pragma mark-set
-(void)setPhotoBlock:(photoBlock)photoBlock
{
    objc_setAssociatedObject(self, &blockKey, photoBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark-get
- (photoBlock )photoBlock
{
    return objc_getAssociatedObject(self, &blockKey);
}
-(void)showCanEdit:(BOOL)edit photo:(photoBlock)block
{
    if(edit) canEdit = edit;
    
    self.photoBlock = [block copy];
    UIActionSheet *sheet  = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"相册中获取", nil];
    sheet.tag = 2599;
    [sheet showInView:self.view];
    
}
#pragma mark - action sheet delegte
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag==2599)
    {
        //权限
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied) {
            NSString *photoType = buttonIndex==0?@"相机":@"相册";
            NSString * title = [NSString stringWithFormat:@"%@权限未开启",photoType];
            NSString * msg = [NSString stringWithFormat:@"请在系统设置中开启该应用%@服务\n(设置->隐私->%@->开启)",photoType,photoType];
            NSString * cancelTitle = @"知道了";
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:cancelTitle otherButtonTitles:nil, nil];
            [alertView show];

            return;
        }
        //跳转到相机/相册页面
        UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = canEdit;
        switch (buttonIndex)
        {
            case 0:
                //拍照
                //是否支持相机
                if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
                {
                    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                    [self presentViewController:imagePickerController animated:YES completion:NULL];
                }
                else
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该设备不支持相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                }
                break;
            case 1:
                //相册
                imagePickerController.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:imagePickerController animated:YES completion:NULL];
            default:
                break;
        }
    }
}
#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image;
    //是否要裁剪
    if ([picker allowsEditing]){
        
        //编辑之后的图像
        image = [info objectForKey:UIImagePickerControllerEditedImage];
        
    } else {
        
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if(self.photoBlock)
    {
        self.photoBlock(image);
    }
}

- (void)didClickBeautysliderValueChange:(MeLivePushWaitView *)vsWaitPushView beautySlider:(UISlider *)slider{
    // todo
    if (slider.tag == 0) { //美颜
        _beauty_level = slider.value;
    } else if (slider.tag == 1) { //美白
        _whitening_level = slider.value;
    }
    
    [_txLivePublisher setBeautyFilterDepth:_beauty_level setWhiteningFilterDepth:_whitening_level];
}

- (void)didClickCameraBtnInWaitPushView:(MeLivePushWaitView *)vsWaitPushView{
    
    [_txLivePublisher switchCamera];
}

- (void)didClickScreenInWaitPushView:(MeLivePushWaitView *)vsWaitPushView gestureRecognizer:(UITapGestureRecognizer *)gestureRecognizer{
    if(_waitPushView.vBeauty.hidden == NO){
        _waitPushView.vBeauty.hidden = YES;
        _waitPushView.bottomView.hidden = NO;
    }
    //手动
    CGPoint touchLocation = [gestureRecognizer locationInView:_videoParentView];
    [_txLivePublisher setFocusPosition:touchLocation];
}


- (void)updateLiveRoomCoverPic{
    //上传
//    SetHUDStartText(@"提交中...")
//    MonkeyQiniuUploader *qiNiuUpload = [[MonkeyQiniuUploader alloc] init];
//    [qiNiuUpload uploadToQiniu:self.imageArrs
//                  aryAudioData:nil
//                  aryVedioData:nil
//                      progress:^(float progress)
//     {
//         DDLogInfo(@"%f=====",progress);
//     } success:^(NSMutableArray *aryImageUrls, NSMutableArray *aryVedioUrls, NSMutableArray *aryAudioUrls)
//     {
//         _myRoomCoverStr = [NSString stringWithFormat:@"%@",[aryImageUrls objectAtIndex:0]];
//         NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//         [parameters setObject:NullStringToString(gProjConfig.dicUserMe[USER_ID]) forKey:@"userid"];
//         [parameters setObject:NullStringToString(_myRoomCoverStr) forKey:@"cover_pic"];
//         _waitPushView.isHaveCover = YES;
//         [[HttpClient manager] POST:@"/live/updateRoomInfo" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//             SetHUDHidden;
//             
//         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//             SetHUDHidden;
//             HUDShowRequestError(error.domain, self.view);
//         }];
//         
//     } failure:^(NSError *error){
//         SetHUDHidden;
//         HUDShowRequestError(error.domain, self.view);
//     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
